package com.yihaodian.server;

import com.yihaodian.api.client.BrokerService;
import com.yihaodian.api.common.Request;
import com.yihaodian.api.common.Response;
import com.yihaodian.api.search.SearchException;
import com.yihaodian.api.search.SugRequest;
import com.yihaodian.api.search.SugResponse;
import com.yihaodian.search.broker.shard.ShardIndexRequest;
import com.yihaodian.search.broker.shard.ShardIndexService;
import com.yihaodian.search.broker.shard.ShardSearchRequest;
import com.yihaodian.search.broker.shard.ShardSearchResponse;
import com.yihaodian.search.broker.shard.ShardSearchService;

/**
 * Connect "Spring" & "Guice" context.
 * 
 */
public class SearchServiceExporter implements ShardSearchService,
		BrokerService, ShardIndexService {

	ShardIndexService shardIndexService;
	ShardSearchService shardSearchService;
	BrokerService brokerService;

	NodeBootstrap nodeBootstrap = null;

	public SearchServiceExporter() {
	}

	/**
	 * create Guice context.
	 * 
	 * @param ip
	 * @param port
	 */
	public void startup(int port) {
		if (nodeBootstrap == null) {
			nodeBootstrap = new NodeBootstrap(port);
			nodeBootstrap.startup();
			shardSearchService = nodeBootstrap.getInjector().getInstance(
					ShardSearchService.class);
			brokerService = nodeBootstrap.getInjector().getInstance(
					BrokerService.class);
			shardIndexService = nodeBootstrap.getInjector().getInstance(
					ShardIndexService.class);
		}
	}

	public NodeBootstrap getNodeBootstrap() {
		return nodeBootstrap;
	}

	@Override
	public Response execute(Request request) throws SearchException {
		return brokerService.execute(request);
	}

	@Override
	public void index(ShardIndexRequest request) throws SearchException {
		shardIndexService.index(request);
	}

	@Override
	public ShardSearchResponse executeSearch(ShardSearchRequest request)
			throws SearchException {
		return shardSearchService.executeSearch(request);
	}

	@Override
	public SugResponse executeSug(String indexName, String shardId,
			SugRequest request) throws SearchException {
		return shardSearchService.executeSug(indexName, shardId, request);
	}
}
